package mysql

import (
	"database/sql"
	"fmt"
	"strings"
)

// 区划表结构体
type ZoningCode struct {
	Id         int
	ZoningName string
	ZoningCode string
	Level      int
	IsDone     int
}

func InitTable() {
	id := 0
	row := MysqlDb.QueryRow("SELECT id FROM `zoning_code` WHERE id=1")
	if err := row.Scan(&id); err == sql.ErrNoRows {
		code := new(ZoningCode)
		code.ZoningName = "中国"
		code.ZoningCode = "100000000000"
		code.Level = 0
		code.IsDone = 0
		Insert(code)
	}
}

// SelectNotDone 查询未完的数据
func SelectNotDone(level int) []*ZoningCode {
	// 通过切片存储
	codeArr := make([]*ZoningCode, 0)
	rows, err := MysqlDb.Query("SELECT id,zoning_name,zoning_code,level,is_done FROM `zoning_code` WHERE is_done=0 and level=? ORDER BY `zoning_code` ASC LIMIT 100", level)
	if err != nil {
		fmt.Println(err)
		return []*ZoningCode{}
	}

	// 遍历
	var code *ZoningCode
	for rows.Next() {
		code = new(ZoningCode)
		rows.Scan(&code.Id, &code.ZoningName, &code.ZoningCode, &code.Level, &code.IsDone)
		codeArr = append(codeArr, code)
	}

	return codeArr
}

// Insert 插入数据
func Insert(code *ZoningCode) {
	_, err := MysqlDb.Exec("INSERT INTO `zoning_code`(zoning_name,zoning_code,level,is_done) VALUES(?,?,?,?)", code.ZoningName, code.ZoningCode, code.Level, code.IsDone)
	if err != nil {
		fmt.Println("添加失败：", err)
	}
}

// InsertAll 批量添加数据
func InsertAll(codeArr []*ZoningCode) {
	sql := []string{}
	for _, code := range codeArr {
		sql = append(sql, fmt.Sprintf("('%s','%s',%d,%d)", code.ZoningName, code.ZoningCode, code.Level, code.IsDone))
	}
	_, err := MysqlDb.Exec("INSERT INTO `zoning_code`(zoning_name,zoning_code,level,is_done) VALUES" + strings.Join(sql, ","))
	if err != nil {
		fmt.Println("批量添加失败：", err)
	}
}

// UpdateDone 更新数据
func UpdateDone(zoningCode string) {
	_, err := MysqlDb.Exec("UPDATE `zoning_code` SET is_done=1 WHERE zoning_code=?", zoningCode)
	if err != nil {
		fmt.Println("更新失败：", err)
	}
}

// DeleteChildren 删除子区划
func DeleteChildren(zoningCode string, level int) {
	_, err := MysqlDb.Exec("DELETE FROM `zoning_code` WHERE zoning_code LIKE ? AND level=?", zoningCode+"%", level)
	if err != nil {
		fmt.Println("删除失败：", err)
	}
}
